# 自己写的认证类，继承某个类

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed, APIException

from libs.yzk_jwt import TokenManager
from .models import UserToken, User


# class LoginAuth(BaseAuthentication):
#     def authenticate(self, request):
#         # 在这里实现认证，如果是登录的，继续往后走返回两个值，如果不是抛异常
#         # 请求中是否携带token，判断是否登录，放在地址栏中
#         token = request.query_params.get('token', None)
#         if token:  # 前端传入token了，去表中查，如果能查到，登录了，返回两个值[固定的：当前登录用户，token]
#             user_token = UserToken.objects.filter(token=token).first()
#             if user_token:
#                 return user_token.user, token
#             else:
#                 # 没有登录抛异常
#                 raise AuthenticationFailed('token认证失败')
#         else:
#             raise AuthenticationFailed('token没传')

# 前端传入的请求头中的数据从哪取？  GET，body，POST，data
class LoginAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', None)
        # print(token)
        if token:
            payload = TokenManager.get_payload(token)
            # user = User.objects.get(pk=payload.get('id'))
            # print(user)
            # return user, token
            if payload is not None:
                user_id = payload.get('id')
                if user_id is not None:
                    user = User.objects.get(pk=user_id)
                    # Rest of your code
                    return user, token
                else:
                    raise AuthenticationFailed(detail="'id' key not found in the token payload.")
            else:
                raise AuthenticationFailed("Payload is None.")
        else:
            raise APIException('没有携带token信息')